import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Table,
  Space,
  Button,
  Input,
  Image,
  Popconfirm,
  Typography,
  Select,
  Tabs,
} from 'antd';
import { SyncOutlined } from '@ant-design/icons';
import { connect, useIntl } from 'umi';
import moment from 'moment';
import IconFont from '@/components/Iconfont';
import { GetFileExt } from '@/services/crud';
import ImgQuick from './imgQuick';
import request from '@/utils/request';

const apiURL = '/api/services/app/Attachment/';
const { Search } = Input;
const { Text } = Typography;

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize] = useState(10);
  const [totalCount, setTotalCount] = useState(0);
  const [keywords, setKeywords] = useState('');
  const [fileExt, setFileExt] = useState([]);
  const [ext, setExt] = useState(null);
  const intl = useIntl();

  useEffect(() => {
    fetchDatas();
    fetchFileExt();
  }, [pageIndex, keywords, ext]);

  const fetchFileExt = async () => {
    const resp = await GetFileExt();
    setFileExt(resp?.result);
  };

  const fetchDatas = () => {
    setLoading(true);
    request(apiURL + 'GetList', {
      method: 'GET',
      params:{ SkipCount: (pageIndex - 1) * pageSize, MaxResultCount: pageSize, keywords, ext }
    }).then((response) => {
      if (response && response.success) {
          setDataSource(response.result.items);
          setTotalCount(response.result.totalCount);
          setLoading(false);
      }
    });
  };

  const handleDelete = (id: number) => {
    request(apiURL + 'Remove', {
      method: 'DELETE',
      params:{ id }
    }).then((response) => {
      fetchDatas();
    });
  };

  const onSelectChange = (selectedRowKeys: any) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  const onSearch = (keywords: any) => {
    setKeywords(keywords);
  };

  const doRefresh = () => {
    setExt(null);
    fetchDatas();
  };

  const imgexe = ['.jpg', '.jpeg', '.png', '.bmp', '.gif'];
  const columns = [
    {
      title: intl.formatMessage({ id: 'pages.file' }),
      width: 60,
      dataIndex: 'sysRowID',
      render: (text: string, record: any) =>
        imgexe.includes(record.fileExtension) ? (
          <Image alt={text} width={60} height={48} src={record.fileUrl} />
        ) : (
          <IconFont
            style={{ fontSize: '30px' }}
            type={'icon-' + record.fileExtension.replace('.', '')}
          />
        ),
    },
    {
      title: intl.formatMessage({ id: 'pages.fileType' }),
      dataIndex: 'fileExtension',
    },
    {
      title: intl.formatMessage({ id: 'pages.objectProperty' }),
      dataIndex: 'objectName',
    },
    {
      title: intl.formatMessage({ id: 'pages.fileSize' }),
      dataIndex: 'fileSize',
      render: (text: string) => (
        <span>
          {text} <Text type="secondary">kb</Text>
        </span>
      ),
    },
    {
      title: intl.formatMessage({ id: 'pages.uploadTime' }),
      dataIndex: 'creationTime',
      render: (text: string) => (
        <span>
          <Text type="secondary">{moment(text).format('YYYY-MM-DD hh:mm:ss')}</Text>
        </span>
      ),
    },
    {
      title: intl.formatMessage({ id: 'pages.fileName' }),
      dataIndex: 'fileName',
    },
    {
      title: intl.formatMessage({ id: 'pages.operation' }),
      render: (record: any) =>
        dataSource.length >= 1 ? (
          <span>
            <Popconfirm title={intl.formatMessage({ id: 'pages.delete?' })} onConfirm={() => handleDelete(record.id)}>
              <a>{intl.formatMessage({ id: 'pages.delete' })}</a>
            </Popconfirm>
          </span>
        ) : null,
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Tabs type="card">
        <Tabs.TabPane tab={intl.formatMessage({ id: 'pages.list' })} key="1">
          <Card>
            <Space>
              <Button
                type="primary"
                onClick={doRefresh}
                loading={loading}
                icon={<SyncOutlined />}
              >
                {intl.formatMessage({ id: 'pages.refresh' })}
              </Button>
              <Select
                style={{ width: 100 }}
                placeholder={intl.formatMessage({ id: 'pages.fileFormat' })}
                onChange={(value) => setExt(value)}
              >
                {fileExt
                  ? fileExt.map((item: any) => {
                      return (
                        <Select.Option key={item} value={item}>
                          {item}
                        </Select.Option>
                      );
                    })
                  : null}
              </Select>
              <Search
                style={{ width: 240 }}
                value={keywords}
                placeholder={intl.formatMessage({ id: 'pages.enterKeywords' })}
                onSearch={(value) => onSearch(value)}
              />
            </Space>
          </Card>
          <Table
            rowKey="id"
            loading={loading}
            rowSelection={rowSelection}
            columns={columns}
            dataSource={dataSource}
            pagination={{
              onChange: (page) => {
                setPageIndex(page);
              },
              pageSize,
              total: totalCount,
            }}
          />
        </Tabs.TabPane>
        <Tabs.TabPane tab={intl.formatMessage({ id: 'pages.thumbnail' })} key="2">
          <ImgQuick gutter={16} column={8} ext=".jpg,.jpeg,.png,.gif" />
        </Tabs.TabPane>
      </Tabs>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
